package com.tanhua.server.service;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSON;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.model.ErrorResult;
import com.tanhua.model.User;
import com.tanhua.server.interceptor.BusinessException;
import com.tanhua.utils.Constants;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.Map;

@Service
public class UserFreezeService {

    @DubboReference
    private UserApi userApi;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    public void checkUserStatus(Integer state,Long userId) {
        String value = redisTemplate.opsForValue().get(Constants.FREEZE_USER + userId);
        if(!StringUtils.isEmpty(value)) {
            Map map = JSON.parseObject(value, Map.class);
            Integer freezingRange = (Integer) map.get("freezingRange");//1 2  3
            if(freezingRange == state) {
                throw new BusinessException(ErrorResult.builder().errMessage("您的账号被冻结！").build());
            }
        }
    }

    @Autowired
    private UserFreezeService userFreezeService;

    /**
     * 发送短信验证码
     *
     * @param phone
     */
    public void sendCode(String phone) {
        //校验用户状态--------------------------
        User user = userApi.findByMobile(phone);
        if (user != null) {
            userFreezeService.checkUserStatus(1,user.getId());
        }

        //1. 生成随机验证码
        //String code = RandomStringUtils.randomNumeric(6);
        String code = "123456";
        //2. 调用阿里云发送验证码
        //判断验证码是否还未失效
        if (redisTemplate.hasKey("CHECK_CODE_" + phone)) {
            throw new RuntimeException("验证码还未失效");
        }
        //smsTemplate.sendSms(phone, code);
        //3. 将验证码保存到redis
        redisTemplate.opsForValue().set("CHECK_CODE_" + phone, code, Duration.ofMinutes(5));
    }
}